# _*_ coding:utf-8 _*_


#
# 信号机制：信号，发送者，接收者==回调函数
# 自定义信号：创建信号，发送，连接回调接收者
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.shortcuts import get_object_or_404
from django.conf import settings
from django.core.mail import EmailMessage
from django.template import loader

from auser.models import User
from movie.models import Review
from post.models import ReviewComment


@receiver(post_save, sender=ReviewComment)
def review_comment_notification(sender, instance, created, **kwargs):
	print('come here')
	if created:
		try:
			rv = get_object_or_404(Review, pk=instance.review_id)
			r_user = rv.user
			ua = get_object_or_404(User, pk=instance.user_id)
		except:
			return False
		else:
			print("yes")
			review_reply_email(r_user.email, "review_reply", template="auser/email/review_reply",
			                         r_user=r_user, c_user=ua, review=rv, c_rm=instance)


# todo: celery 中的share_task
def review_reply_email(to_email, send_type="review_reply", template=None, **kwargs):
	subject = settings.DEFAULT_FROM_EMAIL,
	from_email = settings.EMAIL_HOST_USER
	if send_type == "review_reply":
		email_content = loader.render_to_string(
			template + '.html',
			kwargs,
		)
		email = EmailMessage(subject, email_content, from_email, [to_email])
		email.content_subtype = 'html'
		email.send(fail_silently=False)
